package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import com.xuecheng.ucenter.service.WxAuthService;
import okhttp3.Response;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 微信扫码认证
 */
@Service("wx_authservice")
public class WxAuthServiceImpl implements AuthService , WxAuthService {
    @Autowired
    XcUserMapper xcUserMapper;

    @Value("${weixin.appid}")
    String appid;
    @Value("${weixin.secret}")
    String secret;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto){
        String username = authParamsDto.getUsername();
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername,username));
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);
        return xcUserExt;
    }
    /**
     * 实现微信扫码认证，申请令牌，携带令牌查询用户信息，保存用户信息到数据库
     *
     */
    @Override
    public XcUser wxAuth(String code){
//        申请令牌
        Map<String,String> access_token_map = getAccess_token(code);

//        携带令牌查询用户信息
        String access_token = access_token_map.get("access_token");
        String openid = access_token_map.get("openid");
        Map<String,String> userInfoMap = getUserinfo(access_token,openid);
//        保存用户信息到数据库

        return null;
    }

    /**
     * 携带授权码来申请令牌
     * https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code
     * @param code
     * @return
     * {
     *  "access_token":"ACCESS_TOKEN",
     *  "expires_in":7200,
     *  "refresh_token":"REFRESH_TOKEN",
     *  "openid":"OPENID",
     *  "scope":"SCOPE",
     *  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
     *  }
     */ private Map<String,String> getAccess_token(String code){
          String url_template = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
          String url = String.format(url_template,appid,secret,code);
          //远程调用url
          ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST,null,String.class);
          //获取相应结果
          String result = exchange.getBody();
          //将result转成map
          Map<String,String> map = JSON.parseObject(result,Map.class);
          return map;
    }



    /**
     * 携带令牌查询用户信息
     * https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s
     *
     * {
     *  "openid":"OPENID",
     *  "nickname":"NICKNAME",
     *  "sex":1,
     *  "province":"PROVINCE",
     *  "city":"CITY",
     *  "country":"COUNTRY",
     *  "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
     *  "privilege":[
     *  "PRIVILEGE1",
     *  "PRIVILEGE2"
     *  ],
     *  "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
     *  }
     * @param access_token
     * @param openid
     * @return
     */
    private Map<String,String> getUserinfo(String access_token,String openid){
      String url_template = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
      String url = String.format(url_template,access_token,openid);
      ResponseEntity<String> exchange = restTemplate.exchange(url,HttpMethod.GET,null,String.class);
      String result = exchange.getBody();
      Map<String,String> map = JSON.parseObject(result,Map.class);
      return map;
    }
    @Transactional
    public XcUser addWxUser(Map userInfo_map){
      return null;
    }




}
